package com.qm.console.service.channel.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qm.console.component.util.HttpInvokeUtil;
import com.qm.console.controller.dto.BaseRsp;
import com.qm.console.pubdef.constant.UrlConstant;
import com.qm.console.pubdef.dto.channel.ChannelUpdateAdminDTO;
import com.qm.console.service.channel.ChannelService;
import org.apache.http.client.methods.HttpPut;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ChannelServiceImpl implements ChannelService {
    private final String ChannelAdminUrl="/channels";

    @Override
    public BaseRsp listChannelAdmin(Map<String, String> paramMap) {
        String url= UrlConstant.ApiServerHost+ChannelAdminUrl+"/list";
        String body= HttpInvokeUtil.httpGet(url,paramMap, null);
        BaseRsp rsp= JSONObject.parseObject(body,BaseRsp.class);
        Object rspData=rsp.getData();
        final JSONObject data=(JSONObject) rspData;
        if(data.containsKey("list")){
            JSONArray list= data.getJSONArray("list");
            for(int i=0;i<list.size();i++){
                JSONObject item=list.getJSONObject(i);
                String withDrawId=item.getString("id");
                if(withDrawId!=null){
                    item.put("id",withDrawId);
                }
            }
        }
        return rsp;
    }

    @Override
    public BaseRsp updateChannelAdmin(ChannelUpdateAdminDTO updateDTO){
        String url= UrlConstant.ApiServerHost+ChannelAdminUrl+"/";
        String req= JSONObject.toJSONString(updateDTO);
        String body=HttpInvokeUtil.httpPostJson(url,req,UrlConstant.DefaultEncode,null);
        BaseRsp rsp= JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp DeleteChannelAdmin(String id){
        JSONObject req=JSONObject.parseObject(id);
        String url= UrlConstant.ApiServerHost+ChannelAdminUrl+"/"+req.get("id");
        String body=HttpInvokeUtil.httpDelete(url,null);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp updateChannelStatusAdmin(String updateParam){
        JSONObject paramObj=JSONObject.parseObject(updateParam);
        String url= UrlConstant.ApiServerHost+ChannelAdminUrl+"/"+paramObj.get("id")+"/"+paramObj.get("status");
        HttpPut httpPut=new HttpPut(url);
        String body=HttpInvokeUtil.httpPut(httpPut,UrlConstant.DefaultEncode);
        BaseRsp rsp=JSONObject.parseObject(body,BaseRsp.class);
        return rsp;
    }

}
